import { Component, OnInit, Input } from '@angular/core'
import { Widget } from '../../model'
import { JsonApiService } from '../../../../core/api/json-api.service'

declare var echarts: any
@Component({
  selector: 'installStatistics',
  templateUrl: './installStatistics.html',
  styleUrls: ['./installStatistics.css']
})
export class InstallStatisticsComponent implements OnInit, Widget {
  @Input() componentData: any
  companyIds: any = '' // 选中公司
  time: string = ''
  day: string = ''
  homeTapValue: any = '6'
  selectYear: any //当前选中年
  selectMonth: any //当前选中月
  selectMonthList: any = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
  selectYearList: any = []
  isPrevious: boolean = false //是否禁止跳转上一页
  isNext: boolean = false //是否禁止跳转下一页
  histogramChart: any
  isShowModal: boolean = false //常用项目弹窗
  isLoading: boolean = false

  constructor(private jsonApiService: JsonApiService) {}

  ngOnInit() {
    this.companyIds = this.componentData.componentsConfig
  }

  homeTap(value) {
    var that = this
    that.homeTapValue = value
    that.initYear() //恢复当年
    that.initMonth() //恢复当月
    if (value == 1 || value == 3) {
      that.isNext = true
      that.isPrevious = false

      setTimeout(function () {
        that.initEcharts(1)
      }, 100)
    } else if (value == 2 || value == 4) {
      if (that.selectMonth == 12) {
        that.isNext = true
        that.isPrevious = false
      } else if (that.selectMonth == 1) {
        that.isNext = false
        that.isPrevious = true
      } else {
        that.isNext = false
        that.isPrevious = false
      }

      setTimeout(function () {
        that.initEcharts(2)
      }, 100)
    }
  }

  //获取当前年
  initYear() {
    this.selectYearList = []
    this.selectYear = new Date().getFullYear()

    let lastYear = 2018
    for (let i = 0; i < this.selectYear - lastYear; i++) {
      var nowYear = this.selectYear - i
      this.selectYearList.push(nowYear)
    }
    this.selectYearList.push(lastYear)

    this.isNext = true
  }

  //获取当前月
  initMonth() {
    this.selectMonth = new Date().getMonth() + 1
  }

  jumpPage(type) {
    //跳转上一页还是下一页
    let nowYear = new Date().getFullYear()
    if (type == 1) {
      if (this.isPrevious) {
        return
      }
      this.isNext = false
      if (this.homeTapValue == 1 || this.homeTapValue == 3) {
        this.selectYear = parseInt(this.selectYear) - 1
        if (this.selectYear == 2018) {
          this.isPrevious = true
          this.isNext = false
        }
        this.initEcharts(1)
      }
      if (this.homeTapValue == 2 || this.homeTapValue == 4) {
        this.selectMonth = parseInt(this.selectMonth) - 1
        if (this.selectMonth == 1) {
          this.isPrevious = true
          this.isNext = false
        }
        this.initEcharts(2)
      }
    } else if (type == 2) {
      if (this.isNext) {
        return
      }
      this.isPrevious = false
      if (this.homeTapValue == 1 || this.homeTapValue == 3) {
        this.selectYear = parseInt(this.selectYear) + 1
        if (this.selectYear == nowYear) {
          this.isNext = true
          this.isPrevious = false
        }
        this.initEcharts(1)
      }
      if (this.homeTapValue == 2 || this.homeTapValue == 4) {
        this.selectMonth = parseInt(this.selectMonth) + 1
        if (this.selectMonth == 12) {
          this.isNext = true
          this.isPrevious = false
        }
        this.initEcharts(2)
      }
    }
  }

  chooseYear(value){
		//选择年份
		if(this.homeTapValue == 1 || this.homeTapValue == 3){
			if(value == 2021){
				this.isNext = true;
				this.isPrevious = false;
			}else if(value == 2018){
				this.isPrevious = true;
				this.isNext = false;
			}else{
				this.isPrevious = false;
				this.isNext = false;
			}
			this.initEcharts(1);
		}else{
			this.initEcharts(2);
		}

		
	}
	chooseMonth(value){
		//选择月份
		if(this.homeTapValue == 2 || this.homeTapValue == 4){
			if(value == 1){
				this.isNext = false;
				this.isPrevious = true;
			}else if(value == 12){
				this.isPrevious = false;
				this.isNext = true;
			}else{
				this.isPrevious = false;
				this.isNext = false;
			}
		}

		this.initEcharts(2);
	}

	//返回今年或者今月
	jumpBackYear(){
		this.isNext = true;
		this.isPrevious = false;
		this.selectYear = new Date().getFullYear();
		this.initEcharts(1);
	}

	jumpBackMonth(){
		this.selectMonth = new Date().getMonth() + 1;
		this.selectYear = new Date().getFullYear();
		if(this.selectMonth == 1){
			this.isNext = false;
			this.isPrevious = true;
		}else if(this.selectMonth == 12){
			this.isNext = true;
			this.isPrevious = false;
		}else{
			this.isNext = false;
			this.isPrevious = false;
		}

		this.initEcharts(2);
	}

  currTotalCountList: any = [] //上一年度
  preTotalCountList: any = [] //下一年度
  yoyGrowthRateList: any = [] //上一年度

  //柱状图显示
  initEcharts(type) {
    //创建绘图
    this.histogramChart = echarts.init(document.getElementById('histogramCharts'))
    var parm = {
      queryType: this.homeTapValue,
      year: this.selectYear,
      month: this.selectMonth,
      companyIds: this.companyIds
    }
    this.isLoading = true
    this.jsonApiService
      .http_obj('control/station/install/statistics/installStatistics.html', parm, false)
      .subscribe(result => {
        setTimeout(()=> {
          this.isLoading = false
        },500)
        var resultAttr = result.data
        var currTotalCountAttr = [],
          preTotalCountAttr = [],
          yoyGrowthRateAttr = []
        for (let i = 0; i < resultAttr.length; i++) {
          currTotalCountAttr.push(resultAttr[i].currTotalCount)
          preTotalCountAttr.push(resultAttr[i].preTotalCount)
          if (resultAttr[i].yoyGrowthRate == '') {
            resultAttr[i].yoyGrowthRate = 'null'
          }
          yoyGrowthRateAttr.push(resultAttr[i].yoyGrowthRate)
        }
        this.currTotalCountList = JSON.parse(JSON.stringify(currTotalCountAttr))
        this.preTotalCountList = JSON.parse(JSON.stringify(preTotalCountAttr))
        this.yoyGrowthRateList = JSON.parse(JSON.stringify(yoyGrowthRateAttr))
        var option = this.createEcharts(type, this.selectYear, this.selectMonth)

        this.histogramChart.setOption(option, true)
        $(window).resize(this.histogramChart.resize)
      })
  }

  //柱状图显示的配置
  createEcharts(type, year, month) {
    var title, legendData, xAxisData, sigeTit, itemStyle1, itemStyle2, legendDataName
    var lastYear = year - 1
    if (this.homeTapValue == 1) {
      title = '月安装量同比'
      sigeTit = '安装量/台'
      legendData = [lastYear + '年', year + '年', '月同比增长率']
      legendDataName = {
        月同比增长率: false
      }
      xAxisData = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
      itemStyle1 = {
        normal: {
          label: {
            show: true, //开启显示
            position: 'top', //在上方显示
            textStyle: {
              //数值样式
              color: 'black',
              fontSize: 10
            }
          },
          color: '#3075b4'
        }
      }
      itemStyle2 = {
        normal: {
          label: {
            show: true, //开启显示
            position: 'top', //在上方显示
            textStyle: {
              //数值样式
              color: 'black',
              fontSize: 10
            }
          },
          color: '#c45a20'
        }
      }
    } else if (this.homeTapValue == 2) {
      title = '日安装量同比'
      sigeTit = '安装量/台'
      legendData = [lastYear + '年' + month + '月', year + '年' + month + '月', '日同比增长率']
      legendDataName = {
        日同比增长率: false
      }
      xAxisData = this.getEvryDay(year, month)
      itemStyle1 = {
        normal: {
          label: {
            show: true, //开启显示
            position: 'top', //在上方显示
            textStyle: {
              //数值样式
              color: 'black',
              fontSize: 10
            },
            formatter: function (params) {
              if (params.value > 0) {
                return params.value
              } else {
                return ' '
              }
            }
          },
          color: '#3075b4'
        }
      }
      itemStyle2 = {
        normal: {
          label: {
            show: true, //开启显示
            position: 'top', //在上方显示
            textStyle: {
              //数值样式
              color: 'black',
              fontSize: 10
            },
            formatter: function (params) {
              if (params.value > 0) {
                return params.value
              } else {
                return ' '
              }
            }
          },
          color: '#c45a20'
        }
      }
    } else if (this.homeTapValue == 3) {
      title = '年安装量同比'
      sigeTit = '设备总量/台'
      legendData = [lastYear + '年', year + '年', '月同比增长率']
      legendDataName = {
        月同比增长率: false
      }
      xAxisData = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
      itemStyle1 = {
        normal: {
          label: {
            show: true, //开启显示
            position: 'top', //在上方显示
            rotate: 60,
            distance: 15,
            verticalAlign: 'middle',
            textStyle: {
              //数值样式
              color: 'black',
              fontSize: 10
            },
            formatter: function (params) {
              if (params.value > 0) {
                return params.value
              } else {
                return ' '
              }
            }
          },
          color: '#3075b4'
        }
      }
      itemStyle2 = {
        normal: {
          label: {
            show: true, //开启显示
            position: 'top', //在上方显示
            rotate: 60,
            verticalAlign: 'middle',
            distance: 15,
            textStyle: {
              //数值样式
              color: 'black',
              fontSize: 10
            },
            formatter: function (params) {
              if (params.value > 0) {
                return params.value
              } else {
                return ' '
              }
            }
          },
          color: '#c45a20'
        }
      }
    } else if (this.homeTapValue == 4) {
      title = '设备总量日同比'
      sigeTit = '设备总量/台'
      legendData = [lastYear + '年' + month + '月', year + '年' + month + '月', '日同比增长率']
      legendDataName = {
        日同比增长率: false
      }
      xAxisData = this.getEvryDay(year, month)
      itemStyle1 = {
        normal: {
          label: {
            show: false, //开启显示
            position: 'top', //在上方显示
            textStyle: {
              //数值样式
              color: 'black',
              fontSize: 10
            },
            formatter: function (params) {
              if (params.value > 0) {
                return params.value
              } else {
                return ' '
              }
            }
          },
          color: '#3075b4'
        }
      }
      itemStyle2 = {
        normal: {
          label: {
            show: false, //开启显示
            position: 'top', //在上方显示
            textStyle: {
              //数值样式
              color: 'black',
              fontSize: 10
            },
            formatter: function (params) {
              if (params.value > 0) {
                return params.value
              } else {
                return ' '
              }
            }
          },
          color: '#c45a20'
        }
      }
    }
    var option = {
      title: {
        left: 'center',
        text: title,
        top: 10
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross',
          crossStyle: {
            color: '#999'
          }
        },
        formatter: (params: any) => {
          var res = '';
          for (let i = 0; i < params.length; i++) {
            if (params[i].seriesType === 'line') {
              res = res + params[i].marker + params[i].seriesName + '：' + params[i].data + '%' + '</br>'
            } else {
              res = res + params[i].marker + params[i].seriesName + '：' + params[i].data + '</br>'
            }
          }
          return res
        }
      },
      legend: {
        data: legendData,
        bottom: '10',
        selected: legendDataName
      },
      xAxis: [
        {
          type: 'category',
          data: xAxisData,
          axisPointer: {
            type: 'shadow'
          },
          axisLabel: {
            interval: 0
          }
        }
      ],
      yAxis: [
        {
          type: 'value',
          name: sigeTit,
          nameGap: 30,
          // min: 0,
          // max: maxNum,
          // interval: interval,
          axisLabel: {
            formatter: '{value}'
          }
        },
        {
          type: 'value',
          name: '增长率/%',
          nameGap: 30,
          // min: -10,
          // max: 20,
          // interval: 5,
          axisLabel: {
            formatter: '{value}'
          },
          splitLine: {
            show: false
          }
        }
      ],
      series: [
        {
          name: legendData[0],
          type: 'bar',
          data: this.preTotalCountList,
          itemStyle: itemStyle1,
          barGap: '1%'
        },
        {
          name: legendData[1],
          type: 'bar',
          data: this.currTotalCountList,
          itemStyle: itemStyle2,
          barGap: '1%'
        },
        {
          name: legendData[2],
          type: 'line',
          yAxisIndex: 1,
          data: this.yoyGrowthRateList,
          itemStyle: {
            normal: {
              color: '#1fc359'
            }
          }
        }
      ],
      grid: {
        top: 50,
        right: 40,
        bottom: 60,
        left: 50
      }
    }
    return option
  }

  //获取指定年月的天数
  getDaysInOneMonth(year, month) {
    month = parseInt(month, 10)
    var day = new Date(year, month, 0)
    return day.getDate()
  }

  //获取指定年月的天数 并生成数组
  getEvryDay(year, month) {
    var day
    if (month == 2) {
      day = this.getDaysInOneMonth(year, month)
      var day2 = this.getDaysInOneMonth(year - 1, month)

      if (day2 > day) {
        day = day2
      }
    } else {
      day = this.getDaysInOneMonth(year, month)
    }

    var dayArry = []
    for (var k = 1; k <= day; k++) {
      // var kObj = k+ '日'
      dayArry.push(k)
    }
    return dayArry
  }

  //打开弹窗
  openClick() {
    this.isShowModal = true
  }
  //关闭弹窗
  closeDialog(data) {
    this.isShowModal = data.isShowModal
    const refresh = data.isRefresh
    if (refresh) {
      this.companyIds = data.companyIds
      this.homeTap(this.homeTapValue)
    }
  }
  showLoading(val) {
    setTimeout(() => {
      this.isLoading = val
    });
  }
    
}
